package cn.wind.xboot.framework.formtoken;

import cn.wind.xboot.core.res.ApiResult;
import cn.wind.xboot.core.utils.JsonUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * <p>Title: FormTokenAspect</p>
 * <p>Description: TODO</p>
 *
 * @author xukk
 * @version 1.0
 * @date 2018/8/6
 */
@Aspect
@Component
public class FormTokenAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 对formToken注解的controller执行重复提交验证
     *
     * @param proceedingJoinPoint
     * @param formToken
     * @return
     */
    @Around("@annotation(formToken)")
    public Object execute(ProceedingJoinPoint proceedingJoinPoint, FormToken formToken) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            HttpServletResponse response = attributes.getResponse();
            String authorization=request.getHeader("Authorization");
            if(attributes==null){
                authorization="";
            }
            authorization= authorization.replace("Bearer","").trim();
            String strFormToken = request.getHeader("Form-Token");
            if(strFormToken==null){
                strFormToken="";
            }
            String key="form:token:"+authorization;
            String fff=stringRedisTemplate.opsForValue().get(key);
            response.setCharacterEncoding("UTF-8");
            if (StringUtils.isBlank(strFormToken)) {
                IOUtils.write(JsonUtil.toJson(ApiResult.Custom().failure("表单Token不能为空")),response.getWriter());
                return null;
            }
            if (!StringUtils.equals(strFormToken,fff)) {
                IOUtils.write(JsonUtil.toJson(ApiResult.Custom().failure("请勿重复提交数据!")),response.getWriter());
                return null;
            }
            String newFormToken = UUID.randomUUID().toString();
            response.setHeader("Form-Token", newFormToken);
            stringRedisTemplate.opsForValue().set(key,newFormToken,0);
            return proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            logger.error(e.getMessage());
            return null;
        }
    }
}